package com.newer.veryweather.service;

import java.util.HashMap;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.newer.veryweather.R;
import com.newer.veryweather.Util.Tools;
import com.newer.veryweather.net.NetUtils;
import com.newer.veryweather.net.Weather;
import com.newer.veryweather.ui.WeatherTabActivity;
import com.newer.veryweather.ui.WeatherWidget;

public class WeatherService extends Service {
	public static String ACTION="com.newer.veryweather.service.WeatherService";
	
	Handler UIhandler=null;	//UI线程Handler
	long lastUpdataTime=0;
	
	int weatherUpdataTime=4;//天气更新时间间隔(小时)
	boolean show_notif=true;//是否显示通知栏信息
	String cityId="101010100";	// 默认ID,北京
	boolean auto_update=true;	//是否自动更新
	
	public static Weather weather1=null;		//天气信息的对象
	public static HashMap<String,Weather> weatherMap=null;
	int errCode=0;					//错误代号,0为未出错,其余为出错
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	@Override
	public void onCreate() {
		// 加载首选项,给变量赋值
		loadSetting();
		//
		UIhandler=new Handler();
//		UIhandler.post(timeUpdata);	//更新时间
//		UIhandler.post(weatherUpdata);	//更新天气
		super.onCreate();
	}
	
	/*
	 *	服务命令
	 * 通过Intent传递命令 key= "command",传递的数据key="data";
	 * 	1:发送weather,更新界面
	 * 	2:是否自动更新
	 *  3:更改更新时间
	 *  4:更新已选城市
	 *  5:更改自定义通知
	 *  6:立即更新
	 * 
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent==null){
			return super.onStartCommand(intent, flags, startId);
		}
		int comd=intent.getIntExtra("command", 0);
		
		switch (comd) {
		case 1:	//1:发送weather,更新界面
			sendWeatherBroadCast(weather1,errCode);
			break;
		case 2:	//2:是否自动更新
			auto_update=intent.getBooleanExtra("data", true);
			break;
		case 3:	//3.更改更新时间
			weatherUpdataTime=intent.getIntExtra("data", 4);
			break;
		case 4:	//4.更新已选城市
			String[] citys=intent.getStringArrayExtra("data");
			break;
		case 5:	//5.更改自定义通知
			show_notif=intent.getBooleanExtra("data", false);
			notifi(weather1);
			break;
		case 6:	//6.立即更新
			UIhandler.removeCallbacks(weatherUpdata);
			UIhandler.post(weatherUpdata);			
			break;
		default:
			break;
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
/*
 * 更新时间	
 */
	Runnable timeUpdata=new Runnable() {	//更新Widget时间
		@Override
		public void run() {
			WeatherWidget.updateTime(getApplicationContext());
			UIhandler.postDelayed(this, 10*1000);
		}
	}; 
/*
 * 更新天气	
 */
	Runnable weatherUpdata=new Runnable() {
		@Override
		public void run() {
			new getWeatherThread(cityId).start();// 更新Weather的工作线程
			UIhandler.postDelayed(weatherUpdata, weatherUpdataTime*60*60*1000);
		}
	};
	
	
	/*
	 * 加载设置
	 */
	private void loadSetting(){
		SharedPreferences prefs=getSharedPreferences("weather_pref", MODE_PRIVATE);
		int time=Integer.parseInt(prefs.getString("updata_interval", "4"));
		if(time<1){//如果更新间隔如小于1小时,设为4;
			time=4;
		}
		weatherUpdataTime=time;//更新时间间隔
		show_notif=prefs.getBoolean("show_notif", false);//是否显示自定义通知
		cityId=prefs.getString("currentCity","101010100");//当前城市
		auto_update=prefs.getBoolean("auto_update", true);//是否自动更新
	}
/*
 * weather更新工作线程	
 */
	class getWeatherThread extends Thread{

		String ciTyid=null;
		Weather getedWeather=null;
		public getWeatherThread(String cItyid){
			this.ciTyid=cItyid;
		}
		@Override
		public void run() {
			String jsonStr=null;
			try {
				errCode=0;
				jsonStr = NetUtils.getXmlFromInternet(ciTyid);
//				jsonStr = NetUtils.getXmlFromFile(getApplicationContext(), R.raw.weather);
				getedWeather=NetUtils.parseJson(jsonStr);
			} catch (Exception e) {
				errCode=1;
				e.printStackTrace();
			}
			if(getedWeather!=null){
				weather1=getedWeather;
			}
			//更新完成,更新通知栏,发送天气广播
			notifi(getedWeather);
			sendWeatherBroadCast(getedWeather,errCode);
		}
	}
	
	/*
	 * 发送天气广播,更新小部件和主界面
	 */
	private void sendWeatherBroadCast(Weather tempWeather,int err){
		Intent weatherIntent=new Intent();
		weatherIntent.putExtra("weather", tempWeather);
		weatherIntent.putExtra("err", err);
		weatherIntent.setAction(WeatherWidget.BROADCAST_ACTION);
		sendBroadcast(weatherIntent);
	}
	
	/*
	 * 发送自定义通知
	 */
	private void notifi(Weather notif_weather){
		NotificationManager notifManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		if(notif_weather==null){	//如果天气为空,直接返回不更新或发布通知
			return;
		}
		if(!show_notif){			//如果设置为不显示,取消以显示的亦不发布直接返回
			notifManager.cancel(1);
			return;
		}
    	Notification weatherNotif=new Notification();
    	int weatherIcon=Tools.getPicByIndex(notif_weather.getImgs()[0]);
    	weatherNotif.icon=weatherIcon;
    	RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notifi);
    	contentView.setImageViewResource(R.id.noti_img, weatherIcon);
    	contentView.setTextViewText(R.id.noti_city, notif_weather.getCity());
    	contentView.setTextViewText(R.id.noti_more, notif_weather.getWeatherCons()[0]
    			+" "+notif_weather.getTempsHeight()[0]+"℃"+notif_weather.getTempsLow()[0]+"℃");
    	weatherNotif.contentView = contentView;
    	weatherNotif.flags=Notification.FLAG_NO_CLEAR;
    	
    	Intent notificationIntent = new Intent(this, WeatherTabActivity.class);
    	notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    	weatherNotif.contentIntent = contentIntent;
    	notifManager.notify(1, weatherNotif);
	}
	
	
	
	
}
